'use strict';

/**
 * 系统配置模型
 * @param app
 */
module.exports = app => {
  const { STRING, INTEGER, BOOLEAN, DATE, TEXT, BIGINT } = app.Sequelize;

  const SystemConfig = app.model.define('sys_system_configs', {
    id: {
      type: BIGINT,
      primaryKey: true,
      comment: '配置ID',
    },
    key: {
      type: STRING(50),
      allowNull: false,
      unique: true,
      comment: '配置键',
    },
    value: {
      type: TEXT,
      allowNull: true,
      comment: '配置值',
    },
    name: {
      type: STRING(50),
      allowNull: false,
      comment: '配置名称',
    },
    description: {
      type: STRING(255),
      allowNull: true,
      comment: '配置描述',
    },
    type: {
      type: STRING(20),
      allowNull: false,
      defaultValue: 'string',
      comment: '配置类型：string, number, boolean, json等',
    },
    status: {
      type: BOOLEAN,
      defaultValue: true,
      comment: '状态：true启用，false禁用',
    },
    createTime: {
      type: DATE,
      allowNull: false,
      comment: '创建时间',
      field: 'create_time',
      defaultValue: app.Sequelize.NOW,
    },
    updateTime: {
      type: DATE,
      allowNull: false,
      comment: '更新时间',
      field: 'update_time',
      defaultValue: app.Sequelize.NOW,
    },
  });

  // 在创建前生成雪花ID
  SystemConfig.beforeCreate((systemConfig, options) => {
    const { generateSnowflakeId } = require('../utils/snowflake');
    systemConfig.id = generateSnowflakeId();
  });

  // 自定义toJSON方法，避免字段重复
  SystemConfig.prototype.toJSON = function() {
    const values = Object.assign({}, this.get());
    // 移除重复的下划线字段
    delete values.create_time;
    delete values.update_time;
    return values;
  };

  return SystemConfig;
};

